const userService = require('../service/userService')
const svgCaptcha = require('svg-captcha')
const code = require('../common/code')
const KoaRouter = require('koa-router')

const router = new KoaRouter()

router.post('/login', async (ctx) => {
    const { username = '', password = '', captcha = '' } = ctx.request.body
    if (ctx.session.captcha !== captcha.toLowerCase()) {
        ctx.body = code.getCode(code.CAPTCHA_ERROR)
        return
    }
    const user = await userService.getUserByName(username)
    if (user) {
        if (!user.comparePassword(password)) {
            ctx.body = code.getCode(code.LOGIN_ERROR)
            return
        }
        ctx.session.user = {
            id: user.id,
            role: user.Role.role,
            store_id: user.store_id,
            storeName: user.Store.name,
        }
        ctx.body = code.getCode(code.SUCCESS, null, {
            name: user.name,
            role: user.Role.role,
            store: user.Store.name,
        })
    } else {
        ctx.body = code.getCode(code.LOGIN_ERROR)
    }
})

router.get('/captcha', async (ctx) => {
    const captcha = svgCaptcha.createMathExpr({
        inverse: false, // 翻转颜色
        fontSize: 48, // 字体大小
        noise: 2, // 噪声线条数
        width: 100, // 宽度
        height: 40, // 高度
        size: 4, // 验证码长度
        ignoreChars: '0o1i', // 验证码字符中排除 0o1i
        color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
        background: '#e8e3e3', // 验证码图片背景颜色
    })
    // 保存到session,忽略大小写
    ctx.session.captcha = captcha.text.toLowerCase()
    ctx.body = code.getCode(code.SUCCESS, null, captcha.data)
})

//用户登出
router.get('/logout', async (ctx) => {
    if (ctx.session) {
        delete ctx.session
    }
    ctx.body = code.getCode(code.SUCCESS)
})

module.exports = router
